package com.wenjie.terminal.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

import androidx.core.app.NotificationCompat;

import com.wenjie.terminal.R;
import com.wenjie.terminal.config.App;
import com.wenjie.terminal.entity.HandlerMessage;
import com.wenjie.terminal.entity.enums.HandlerMessageType;

import java.io.IOException;

/**
 * HTTP服务
 */
public class HttpServerService extends Service {

    private static final String CHANNEL_ID = "HTTP_SERVER_CHANNEL_ID";
    private static final int SERVICE_ID = 1;

    private App app;
    private HttpServer httpServer;

    public HttpServerService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();

        Context context = this.getApplicationContext();
        app = (App) context;

        // 创建一个通知渠道
        String channelName = "自助终端服务";
        // 高优先级通知
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, channelName, importance);

        NotificationManager manager = getSystemService(NotificationManager.class);
        if (manager != null) {
            manager.createNotificationChannel(channel);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Messenger messenger = null;
        if (intent != null) {
            messenger = intent.getParcelableExtra("handlerMessenger");
        }

        // 启动前台服务
        startForegroundService();

        // 启动HTTP服务
        try {
            httpServer = new HttpServer(app);

            if (messenger != null) {
                HandlerMessage message = new HandlerMessage();
                message.setMessageType(HandlerMessageType.GO_WEB_VIEW);

                Message targetMsg = Message.obtain();
                targetMsg.obj = message;

                try {
                    messenger.send(targetMsg);
                } catch (RemoteException ex) {
                    ex.printStackTrace();
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();

            if (messenger != null) {
                HandlerMessage message = new HandlerMessage();
                message.setMessageType(HandlerMessageType.TEXT_TIP);
                message.setMessage("无法启动系统关键服务，请重启系统再次尝试");

                Message targetMsg = Message.obtain();
                targetMsg.obj = message;

                try {
                    messenger.send(targetMsg);
                } catch (RemoteException ex1) {
                    ex1.printStackTrace();
                }
            }

            stopForeground(Service.STOP_FOREGROUND_REMOVE);
        }

        // 确保服务异常退出后能重启
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 服务销毁时的清理操作

        if (httpServer != null) {
            httpServer.stop();
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 启动前台服务
     */
    private void startForegroundService() {
        // 创建一个通知，显示服务正在运行
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("自助终端服务")
                .setContentText("服务正在运行")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .build();

        // 将服务设置为前台服务
        startForeground(SERVICE_ID, notification);
    }
}